import 'dart:io';

import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:process_run/shell.dart';

import '../common/app.dart';
import '../ext/dialog_ext.dart';
import '../widgets/app_dialog.dart';

class BaseViewModel extends ChangeNotifier {
  String? get userHome => Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
  BuildContext context;
  late Shell shell;
  var adbPath = "";

  bool _isLoading = false;

  bool get isLoading => _isLoading;

  void showLoading({String? text}) {
    _isLoading = true;
    loadingText = text ?? "";
    notifyListeners();
  }

  void dismissLoading() {
    _isLoading = false;
    notifyListeners();
  }

  String loadingText = "";

  BaseViewModel(this.context) {
    shell = Shell(
      workingDirectory: userHome,
      environment: Platform.environment,
      throwOnError: false,
      runInShell: false
    );
    App().getAdbPath().then((value) => adbPath = value);
  }

  /// 安装apk
  void installApk(String deviceId, String path) async {
    if (path.isNotEmpty) {
      var result = await execAdb(['-s', deviceId, 'install', '-r', '-d', path]);
      if (result?.exitCode == 0) {
        /// 刷新已安装应用
        App().eventBus.fire("refresh");
        showResultDialog(
          title: "提示",
          content: "安装成功",
        );
      } else {
        showResultDialog(
          title: "安装失败",
          content: result?.stdout ?? "",
        );
      }
    }
  }

  /// 执行adb
  Future<ProcessResult?> execAdb(List<String> arguments, {void Function(Process process)? onProcess,    bool isShowLoading = true,}) async {
    if (adbPath.isEmpty) {
      showResultDialog(
        title: "ADB没有找到",
        content: "请配置ADB环境变量",
      );
      return null;
    }
    return await exec(adbPath, arguments, onProcess: onProcess,isShowLoading: isShowLoading);
  }

  /// 执行命令
  Future<ProcessResult?> exec(
    String executable,
    List<String> arguments, {
    String loadingText = "执行中...",
    bool isShowLoading = true,
    void Function(Process process)? onProcess,
  }) async {
    if (isShowLoading) {
      showLoading(text: loadingText);
    }

    try {
      return await shell.runExecutableArguments(executable, arguments, onProcess: onProcess);
    } catch (e) {
      // showResultDialog(content: "命令执行异常："+e.toString());
      print("异常=" + e.toString());
      return null;
    } finally {
      if (isShowLoading) {
        dismissLoading();
      }
    }
  }

  /// 弹出提示框
  void showResultDialog({String? title, String? content, bool? isSuccess}) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AppDialog(
          title: title,
          content: content ?? (isSuccess == true ? "操作成功" : "操作失败"),
        );
      },
    );
  }

  Future<bool?> showInstallApkDialog(String deviceId, XFile file) async {
    await showAlertDialog(
        context: context,
        content: '是否安装${file.name}?',
        cancelText: "取消",
        onConfirm: () {
          installApk(deviceId, file.path);
        });
  }
}
